package org.pathlet.jdbc.example.impl;

import java.io.IOException;
import java.util.List;

import javax.sql.DataSource;


import org.springframework.transaction.annotation.Transactional;

import org.pathlet.jdbc.example.UserService;
import org.pathlet.jdbc.example.vo.UserVO;
import org.pathlet.jdbc.EntityInsertDef;
import org.pathlet.jdbc.EntityRowMapper;
import org.pathlet.jdbc.EntityUpdateDef;
import org.pathlet.jdbc.ExtJdbcTemplate;
import org.pathlet.util.ValueUtils;

@Transactional
public class UserServiceImpl implements UserService {

	private ExtJdbcTemplate jdbcTemplate;

	public void setDataSource(DataSource dataSource) throws IOException {

		this.jdbcTemplate = new ExtJdbcTemplate(dataSource);

		this.jdbcTemplate.registerInsertEntity(
				new EntityInsertDef("T_USER", UserVO.class, "T_USER"));

		this.jdbcTemplate.registerUpdateEntity(
				new EntityUpdateDef("T_USER", UserVO.class, "T_USER", new String[] {"username"}));

	}

	public void deleteUsers(String[] usernames) {
		for(String username : usernames) {
			jdbcTemplate.update("DELETE from T_USER where USERNAME= ?", new Object[] { username });
		}
	}

	@Transactional(readOnly=true)
	public UserVO getUser(String username, String password) {
		return (UserVO)this.jdbcTemplate.queryForObject(
				"select * from T_USER where USERNAME=? and PASSWORD=?",
				new Object[]{username, password}, new EntityRowMapper(UserVO.class, null));
	}

	@Transactional(readOnly=true)
	public UserVO getUser(String username) {
		UserVO user = (UserVO)this.jdbcTemplate.queryForObject(
				"select t.* from T_USER t where USERNAME=?",
				new Object[]{username}, new EntityRowMapper(UserVO.class, null));
		return user;
	}


	public void saveUser(UserVO user) {
		jdbcTemplate.insertEntity("T_USER", user);
	}

	public void updateUser(UserVO user) {
		jdbcTemplate.updateEntity("T_USER", user);
	}

}
